package com.haian.slidealbum.control;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.haian.slidealbum.R;
import com.haian.slidealbum.common.ConstCommon;
import com.haian.slidealbum.common.UtilsCommon;
import com.haian.slidealbum.model.adapter.AdapterFlickrUpdate;
import com.haian.slidealbum.model.delegate.ServiceDelegate;
import com.haian.slidealbum.model.helper.DBHandler;
import com.haian.slidealbum.model.object.ObjectFlickrImage;
import com.haian.slidealbum.model.object.ObjectImage;

public class FlickrImageUpdateActivity extends Activity implements
		OnClickListener {

	GridView gridContent;
	AdapterFlickrUpdate adapter;
	TextView txtItemSelected, txtDone;
	ArrayList<ObjectFlickrImage> arrayImage, arrayImageSelected;
	ArrayList<ObjectImage> arrayImageClient;
	Dialog dialog; //dialogDownload;
	Context mContext;
	String idAlbumOfServer;
	String access_token;
	String urlFolder;
	int idAlbum;
	ViewFlipper vf;
	int LOADING = 0, CONTENT = 1, ERRO = 2;

	// ____________________ System Function _____________________________

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_flickr);
		initWidget();
		initDB();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.txtDone:
			showDialogAlbum();
			break;

		default:
			break;
		}

	}

	// ________________________ Custom Function ______________

	// download file
	public void downloadFile(final int maxIdAlbum) {
		try {
//			dialogDownload = ProgressDialog.show(this, "",mContext.getResources().getString(R.string.downloading_file), true);

			final String urlFolder = UtilsCommon.createFolder(getString(R.string.flick));
			new Thread(new Runnable() {
				public void run() {
					for (int i = 0; i < arrayImageSelected.size(); i++) {
						ObjectFlickrImage mObjectFlickrImage = arrayImageSelected
								.get(i);
						String urlDownload = mObjectFlickrImage
								.getImage_source();
						boolean checkStatus = UtilsCommon.downLoadFile(
								FlickrImageUpdateActivity.this, urlDownload,
								urlFolder);
						if (checkStatus != false) {
							Log.d("Luong",
									"************************ download image: "
											+ mObjectFlickrImage
													.getImage_source());
							String itemCover = "0";
							if (i == 0) {
								itemCover = "1";
							}
							ObjectImage mObjectImage = new ObjectImage();
							mObjectImage.setUrlImage(urlFolder
									+ "/"
									+ urlDownload.substring(urlDownload
											.lastIndexOf("/")));
							arrayImageClient.add(mObjectImage);
							DBHandler.insertItem(mContext,
									mObjectImage.getUrlImage(),
									String.valueOf(maxIdAlbum), itemCover);
						} else {
							Log.e("Luong",
									"************************ download image fail: "
											+ mObjectFlickrImage
													.getImage_source());
						}
					}
//					dialogDownload.dismiss();
				}
			}).start();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	private void initWidget() {
		vf = (ViewFlipper) findViewById(R.id.vf);
		vf.setDisplayedChild(LOADING);
		arrayImage = new ArrayList<ObjectFlickrImage>();
		arrayImageClient = new ArrayList<ObjectImage>();
		mContext = this;
		txtItemSelected = (TextView) findViewById(R.id.txtItemSelected);
		txtItemSelected.setOnClickListener(this);
		txtDone = (TextView) findViewById(R.id.txtDone);
		txtDone.setOnClickListener(this);
	}

	private void initDB() {
		try {
			Intent intent = new Intent();
			intent = getIntent();
			idAlbumOfServer = intent.getExtras().getString(
					ConstCommon.KEY_RESULT_ID_ALBUM);
			access_token = intent.getExtras().getString(
					ServiceDelegate.KEY_ACCESS_TOKEN);
			idAlbum = intent.getExtras().getInt(ServiceDelegate.KEY_ID);
			ServiceDelegate.getFlickrImage(mhandlerImage, idAlbumOfServer);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public ArrayList<ObjectFlickrImage> getListImageSelected() {
		ArrayList<ObjectFlickrImage> listImageSelected = new ArrayList<ObjectFlickrImage>();
		try {
			if (arrayImage.size() > 0) {
				for (int i = 0; i < arrayImage.size(); i++) {
					if (arrayImage.get(i).isSelected()) {
						listImageSelected.add(arrayImage.get(i));
					}
				}
			}
			txtItemSelected.setText(listImageSelected.size() + " " + getResources().getString(R.string.selected));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return listImageSelected;
	}

	void showDialogAlbum() {
		try {
			if (idAlbum > 0) {
				arrayImageSelected = getListImageSelected();
				if (arrayImageSelected.size() > 0) {
					arrayImageClient = new ArrayList<ObjectImage>();
					downloadFile(idAlbum);
					// change status service widget
					WidgetUpdateService.statusCurrentAlbum = true;
					updateListImage(idAlbum);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	void updateListImage(int idAlbum) {
		Intent returnIntent = new Intent();
		returnIntent.putExtra(ConstCommon.KEY_RESULT_ID_ALBUM, idAlbum);
		setResult(RESULT_OK, returnIntent);
		finish();
	}

	Handler mhandlerImage = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 0) {
				try {
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;
					String status = dataJSONObject
							.getString(ServiceDelegate.KEY_STAT);
					if (status.equals("ok")) {
						JSONObject photosetJSONObject = new JSONObject();
						photosetJSONObject = dataJSONObject
								.getJSONObject(ServiceDelegate.KEY_PHONESET);

						JSONArray photoJSONArray = new JSONArray();
						photoJSONArray = photosetJSONObject
								.getJSONArray(ServiceDelegate.KEY_PHOTO);
						int totalPhoto = photoJSONArray.length();
						if (totalPhoto > 0) {
							arrayImage = new ArrayList<ObjectFlickrImage>();
							for (int i = 0; i < totalPhoto; i++) {
								ObjectFlickrImage mObjectFlickrImage = new ObjectFlickrImage();

								JSONObject photoJSONObject = new JSONObject();
								photoJSONObject = (JSONObject) photoJSONArray
										.get(i);
								String farm = photoJSONObject
										.getString(ServiceDelegate.KEY_FARM);
								String server = photoJSONObject
										.getString(ServiceDelegate.KEY_SERVER);
								String id = photoJSONObject
										.getString(ServiceDelegate.KEY_ID);
								String secret = photoJSONObject
										.getString(ServiceDelegate.KEY_SECRET);
								String urlIMG = "http://farm" + farm
										+ ".staticflickr.com/" + server + "/"
										+ id + "_" + secret + ".jpg";
								mObjectFlickrImage.setImage_source(urlIMG);
								mObjectFlickrImage.setSelected(false);
								arrayImage.add(mObjectFlickrImage);
							}
							if (arrayImage.size() > 0) {
								vf.setDisplayedChild(CONTENT);
								adapter = new AdapterFlickrUpdate(
										FlickrImageUpdateActivity.this,
										arrayImage);
								gridContent = (GridView) findViewById(R.id.gridContent);
								gridContent.setFastScrollEnabled(true);
								gridContent.setAdapter(adapter);
							} else {
								vf.setDisplayedChild(ERRO);
							}
						} else {
							vf.setDisplayedChild(ERRO);
						}

					} else {
						vf.setDisplayedChild(ERRO);
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
	};
}